﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System.Web;
using Nancy.Json;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Http;

namespace BCCServer.Common.Common
{

    public class TokenInfo
    {
        public string? UserName { get; set; }
        public Double iat { get; set; }
        public Double exp { get; set; }
    }

    public class TokenHelper
    {
        public static string SecretKey = "bcc3k12s0h1d3uhf493fh02hdd102h9s3h38ff";//这个服务端加密秘钥 属于私钥
        private static JavaScriptSerializer myJson = new JavaScriptSerializer();

        /// <summary>
        /// 生成Token
        /// </summary>
        /// <param name="M"></param>
        /// <returns></returns>
        public static string GenToken(TokenInfo M)
        {
            var jwtcreated = Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + 5);
            var jwtcreatedOver = Math.Round((DateTime.UtcNow.AddHours(15) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + 5);
            var payload = new Dictionary<string, dynamic>
            {
                {"UserName", M.UserName},   //用于存放当前登录人账户信息
                {"iat", jwtcreated },       //签发时间
                {"exp", jwtcreatedOver }    //过期时间    
            };
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(payload, SecretKey);
        }
        /// <summary>
        /// 验证Token
        /// </summary>
        /// <returns></returns>
        public static int DecodeToken(AuthorizationFilterContext context)
        {
            string token = "";

            //获取request中的token
            token = context.HttpContext.Request.Headers["Authorization"];
            //去掉前面的Bearer
            if (token != null && token.StartsWith("Bearer"))
            {
                token = token.Substring("Bearer ".Length).Trim();
                //var json = GetTokenJson(token);
                try
                {
                    var json = GetTokenJson(token);
                    TokenInfo info = myJson.Deserialize<TokenInfo>(json);
                    return StatusCodes.Status100Continue; //Token is true
                }
                catch (TokenExpiredException)
                {
                    return StatusCodes.Status403Forbidden;//Token has expired
                }
                catch (SignatureVerificationException)
                {
                    return StatusCodes.Status401Unauthorized;//Token has invalid signature
                }
            }
            else
            {
                return StatusCodes.Status401Unauthorized ;
            }
        }

        public static string GetTokenJson(string token)
        {
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                var json = decoder.Decode(token, SecretKey, verify: true);
                return json;
            }
            catch (Exception e)
            {
                //LogHelper.Info(e.Message);
                //return "501";
                throw;
            }
        }

        

    }

}
